<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '完善个人资料',
  },
}
</route>

<template>
  <view class="bg-white" :class="[{ 'dark-color': themeConfig.theme === 'dark' }]">
    <!-- <wd-sticky :offset-top="-43">
      <view class="w-100vw bg-#fff mt--1px" :class="[{ 'dark-color': themeConfig.theme === 'dark' }]">
        <view class="w-center flex-center font-size-26rpx py-24rpx">
          <view class="w-150rpx">置顶推荐分</view>
          <view class="" style="flex: 1;">
            <wd-progress custom-class="percentage-wrap" :percentage="getScore" hide-text></wd-progress>
          </view>
          <view class="w-74rpx text-right color-#986DF0">{{ getScore }}分</view>
        </view>
      </view>
    </wd-sticky> -->

    <view class="w-750rpx m-a pl-32rpx pr-32rpx box-border font-size-28rpx font-600 pt-20rpx pb-20rpx">个人头像</view>
    <view class="w-750rpx m-a box-border flex-sb-center pl-64rpx pr-64rpx box-border">
      <view class="w-248rpx h-200rpx bg-#FAF7FF flex-center relative"
        :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
      >
        <wd-img width="100%" height="100%" mode='aspectFit' :src="user.getUseVo.personAvatar.preUrl" :enable-preview="true" @click.stop="" />
        <view class="position-center w-1/2 h-1/2 flex-center" @click="uploadAvatar()">
          <wd-icon name="add" size="18px" v-if="!user.getUseVo.personAvatar.preUrl"></wd-icon>
        </view>
        <!-- <view class="absolute left-12rpx top-6rpx font-size-20rpx"
          :class="[user.getUseVo.personAvatar.preUrl ? 'color-#986DF0' : 'color-#666']"
        >+{{ scoreOption.personAvatar }}分</view> -->
      </view>
    </view>
    
    <view class="w-750rpx m-a pl-32rpx pr-32rpx box-border font-size-28rpx font-600 pt-20rpx pb-20rpx">个人形象照片</view>
    <view class="w-750rpx m-a box-border flex-sb-center pl-64rpx pr-64rpx box-border"
      :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
    >
      <view class="w-248rpx h-200rpx bg-#FAF7FF flex-center relative"
        :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
      >
        <wd-img width="100%" height="100%" mode='aspectFit' :src="getFileOptions(1).preUrl" />
        <view class="position-center w-1/2 h-1/2 flex-center" @click="deleteConfirm(1)" v-if="getFileOptions(1).preUrl">
          <!-- <wd-icon name="delete-thin" size="18px"></wd-icon> -->
        </view>
        <view class="position-center w-1/2 h-1/2 flex-center" @click="uploadImg(1)" v-else>
          <wd-icon name="add" size="18px"></wd-icon>
        </view>
        <!-- <view class="absolute left-12rpx top-6rpx font-size-18rpx"
          :class="[getFileOptions(1).preUrl ? 'color-#986DF0' : 'color-#666']"
        >+{{ scoreOption.personImg }}分</view> -->
      </view>

      <view class="w-129rpx h-200rpx flex-sb flex-col flex-wrap">
        <view class="w-129rpx h-95rpx bg-#FAF7FF flex-center relative"
          :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
        >
          <wd-img width="100%" height="100%" mode='aspectFit' :src="getFileOptions(2).preUrl" />
          <view class="position-center w-1/2 h-1/2 flex-center" @click="deleteConfirm(2)" v-if="getFileOptions(2).preUrl">
            <!-- <wd-icon name="delete-thin" size="16px"></wd-icon> -->
          </view>
          <view class="position-center w-1/2 h-1/2 flex-center" @click="uploadImg(2)" v-else>
            <wd-icon name="add" size="16px"></wd-icon>
          </view>
          <!-- <view class="absolute left-12rpx top-6rpx font-size-18rpx"
            :class="[getFileOptions(2).preUrl ? 'color-#986DF0' : 'color-#666']"
          >+{{ scoreOption.personImg }}分</view> -->
        </view>
        
        <view class="w-129rpx h-95rpx bg-#FAF7FF flex-center relative"
          :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
        >
          <wd-img width="100%" height="100%" mode='aspectFit' :src="getFileOptions(3).preUrl" />
          <view class="position-center w-1/2 h-1/2 flex-center" @click="deleteConfirm(3)" v-if="getFileOptions(3).preUrl">
            <!-- <wd-icon name="delete-thin" size="16px"></wd-icon> -->
          </view>
          <view class="position-center w-1/2 h-1/2 flex-center" @click="uploadImg(3)" v-else>
            <wd-icon name="add" size="16px"></wd-icon>
          </view>
          <!-- <view class="absolute left-12rpx top-6rpx font-size-18rpx"
            :class="[getFileOptions(3).preUrl ? 'color-#986DF0' : 'color-#666']"
          >+{{ scoreOption.personImg }}分</view> -->
        </view>
      </view>
      
      <view class="w-129rpx h-200rpx flex-sb flex-col flex-wrap">
        <view class="w-129rpx h-95rpx bg-#FAF7FF flex-center relative"
          :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
        >
          <wd-img width="100%" height="100%" mode='aspectFit' :src="getFileOptions(4).preUrl" />
          <view class="position-center w-1/2 h-1/2 flex-center" @click="deleteConfirm(4)" v-if="getFileOptions(4).preUrl">
            <!-- <wd-icon name="delete-thin" size="16px"></wd-icon> -->
          </view>
          <view class="position-center w-1/2 h-1/2 flex-center" @click="uploadImg(4)" v-else>
            <wd-icon name="add" size="16px"></wd-icon>
          </view>
          <!-- <view class="absolute left-12rpx top-6rpx font-size-18rpx"
            :class="[getFileOptions(4).preUrl ? 'color-#986DF0' : 'color-#666']"
          >+{{ scoreOption.personImg }}分</view> -->
        </view>
        
        <view class="w-129rpx h-95rpx bg-#FAF7FF flex-center relative"
          :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
        >
          <wd-img width="100%" height="100%" mode='aspectFit' :src="getFileOptions(5).preUrl" />
          <view class="position-center w-1/2 h-1/2 flex-center" @click="deleteConfirm(5)" v-if="getFileOptions(5).preUrl">
            <!-- <wd-icon name="delete-thin" size="16px"></wd-icon> -->
          </view>
          <view class="position-center w-1/2 h-1/2 flex-center" @click="uploadImg(5)" v-else>
            <wd-icon name="add" size="16px"></wd-icon>
          </view>
          <!-- <view class="absolute left-12rpx top-6rpx font-size-18rpx"
            :class="[getFileOptions(5).preUrl ? 'color-#986DF0' : 'color-#666']"
          >+{{ scoreOption.personImg }}分</view> -->
        </view>
      </view>
    </view>

    <view class="w-750rpx m-a pl-32rpx pr-32rpx box-border font-size-28rpx font-600 pt-20rpx pb-20rpx">个人情况</view>
    <wd-form ref="formRefs" :model="formData" :errorType="errorType">
      <wd-input 
        align-right 
        type="text" 
        label="昵称" 
        prop="nickname"
        v-model="formData.nickname" 
        :maxlength="8"
        placeholder="请输入昵称" 
        :rules="[{ required: true, message: '请输入昵称！' }]"
      />
      <view class="border-1px"></view>
      <view class="w-750rpx m-a">
        <view class="w-center pt-22rpx pb-22rpx flex-sb-center">
          <view class="font-size-28rpx">
            <text class="font-size-15px color-#fa4350">*</text>
            性别
          </view>
          <wd-radio-group v-model="formData.gender" inline shape="dot">
            <wd-radio value="0">男</wd-radio>
            <wd-radio value="1">女</wd-radio>
          </wd-radio-group>
        </view>
        <view class="border-1px"></view>
      </view>
      <wd-cell 
        title="身高体重" 
        required 
        :value="`
          ${ user.heightInfo.height ? user.heightInfo.height + 'cm' : '请选择' }/
          ${ user.heightInfo.weight ? user.heightInfo.weight + 'kg' : '请选择' }
        `" 
        is-link 
        to="/feature/weight?type=heightInfo"
      ></wd-cell>
      <view class="border-1px"></view>

      <wd-cell 
        title="毕业院校(非必填项)" 
        :value="schoolName ? schoolName : '请选择'" 
        is-link 
        :to="`/feature/school?type=school&typeCode=${formData.school}`"
      ></wd-cell>
      <view class="border-1px"></view>
      
      <wd-cell 
        title="行业/职业" 
        required 
        :value="professionName ? professionName : '请选择'" 
        is-link 
        :to="`/feature/school?type=profession&typeCode=${formData.profession}`"
      ></wd-cell>
      <view class="border-1px"></view>

      <wd-datetime-picker 
        label="出生年月" 
        align-right 
        prop="birthYearMonth"
        type="date"
        :minDate="-662688000000"
        v-model="formData.birthYearMonth" 
        :rules="[{ required: true, message: '请选择出生年月！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-cell 
        title="居住地" 
        required 
        :value="city ? city : '请选择'" 
        is-link 
        :to="`/feature/areaPicker?isAll=1&isRequired=2&areaStr=${[formData.provinceId,formData.cityId,formData.districtId].filter(item => !!item).join(',')}`"
      ></wd-cell>
      <view class="border-1px"></view>

      <wd-picker 
        align-right 
        :columns="useCommon.commonState.dictInfo['matrimony']" 
        label="婚姻状况" 
        v-model="formData.maritalStatus" 
        prop="maritalStatus"
        :rules="[{ required: true, message: '请选择婚姻状况！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-picker 
        align-right 
        :columns="useCommon.commonState.dictInfo['education']" 
        label="最高学历" 
        v-model="formData.educationLevel" 
        prop="educationLevel"
        :rules="[{ required: true, message: '请选择最高学历！' }]"
        label-width="280rpx"
      />
      <view class="border-1px"></view>
      
      <wd-picker 
        align-right 
        :columns="useCommon.commonState.dictInfo['income']" 
        label="年收入" 
        v-model="formData.incomeStatus" 
        prop="incomeStatus"
        :rules="[{ required: true, message: '请选择年收入！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-picker 
        align-right 
        :columns="useCommon.commonState.dictInfo['assets']" 
        label="车房情况" 
        v-model="formData.carHouseStatus" 
        prop="carHouseStatus"
        :rules="[{ required: true, message: '请选择车房情况！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-picker 
        align-right 
        :columns="useCommon.commonState.dictInfo['educationType']" 
        label="教育类型" 
        v-model="formData.educationType" 
        prop="educationType"
        :rules="[{ required: true, message: '请选择教育类型！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-picker 
        align-right 
        :columns="useCommon.commonState.dictInfo['publish_people_type']" 
        label="发布人" 
        v-model="formData.publishPeopleType" 
        prop="publishPeopleType"
        :rules="[{ required: true, message: '请选择发布人！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-cell title="择偶要求" required :value="preferences" is-link to="/feature/require"></wd-cell>
      <view class="border-1px"></view>

      <!-- <view class="w-750rpx m-a pl-32rpx pr-32rpx box-border font-size-28rpx font-600 pt-20rpx">
        <text class="font-size-15px color-#fa4350">*</text>
        择偶要求描述
      </view>
      <view class="w-center !mt-20rpx">
        <wd-textarea 
          placeholderStyle="font-size: 28rpx" 
          v-model="formData.partnerRequirements" 
          placeholder="请放宽择偶要求，婚姻最后拼的都是人品" 
          prop="partnerRequirements"
          :rules="[{ required: true, message: '请输入择偶要求描述！' }]"
        />
      </view> -->
      
      <view class="w-750rpx m-a pl-32rpx pr-32rpx box-border font-size-28rpx font-600 pt-20rpx">
        <text class="font-size-15px color-#fa4350">*</text>
        关于我
      </view>
      <view class="w-center !mt-20rpx">
        <wd-textarea 
          placeholderStyle="font-size: 28rpx" 
          v-model="formData.specialNote" 
          placeholder="讲讲你的经历、性格和兴趣爱好吧" 
          prop="specialNote"
          :rules="[{ required: true, message: '请输入关于我的简介！' }]"
        />
      </view>

      <view class="w-750rpx m-a pl-32rpx pr-32rpx box-border font-size-28rpx font-600 pt-20rpx">
        <text class="font-size-15px color-#fa4350">*</text>
        我的爱情观
      </view>
      <view class="w-center !mt-20rpx">
        <wd-textarea 
          placeholderStyle="font-size: 28rpx" 
          v-model="formData.loveView" 
          placeholder="对于爱情和婚姻，你的观点和态度是什么？" 
          prop="loveView"
          :rules="[{ required: true, message: '请输入爱情观！' }]"
        />
      </view>

      <view class="w-750rpx m-a pl-32rpx pr-32rpx box-border font-size-28rpx font-600 pt-20rpx">
        <text class="font-size-15px color-#fa4350">*</text>
        理想中的Ta
      </view>
      <view class="w-center !mt-20rpx">
        <wd-textarea 
          placeholderStyle="font-size: 28rpx" 
          v-model="formData.idealPartner" 
          placeholder="说说你理想中的另一半是什么样子" 
          prop="idealPartner"
          :rules="[{ required: true, message: '请输入理想中的Ta！' }]"
        />
      </view>
    </wd-form>
    
    <view class="w-750rpx m-a pl-32rpx pr-32rpx box-border font-size-28rpx font-600 pt-20rpx pb-20rpx">请留下你的联系方式</view>
    <view class="w-center font-size-24rpx color-#666">
      <view class="">当心仪的人想要联系你时，此联系方式将直接提供给对方</view>
      <view class="font-600">微信二维码和手机号必须二选一</view>
      <!-- <view class="">如留下联系方式，当候选人想要联系你时，此联系方式会直接提供给对方，没有预留联系方式时，他将无法联系到你。</view> -->
      <view class="mt-12rpx">
        <wd-checkbox 
          v-model="formData.showPhone" 
          shape="square" 
          @change="(val) => handleChangeContact(val, 'showPhone')"
        >提供电话号码</wd-checkbox>
      </view>
    </view>
    <view class="flex-center pt-32rpx text-center font-size-28rpx">
      <wd-text :text="user.userInfo.phone" mode="phone" :format="true"></wd-text>
      <text class="ml-32rpx color-#9C6DEF"
        @click="toPath('/feature/changePhone')"
      >更换号码</text>
    </view>
    
    <view class="w-center font-size-24rpx color-#666 pt-20rpx">
      <view class="mt-12rpx">
        <wd-checkbox 
          v-model="formData.showWechat" 
          shape="square"
          @change="(val) => handleChangeContact(val, 'showWechat')"
        >提供微信二维码</wd-checkbox>
      </view>
      <view class="pt-20rpx">请打开微信，点开“我”，点击保存你的微信头像，选择“我的二维码”，最后点击右下角的“保存图片”，这个图片就是你的微信二维码。微信二维码用于征婚者联系你使用</view>
    </view>
    
    <view class="w-750rpx m-a box-border flex-sb-center pl-64rpx pr-64rpx box-border mt-24rpx">
      <wd-upload 
        :file-list="qrcodeFileList" 
        image-mode="aspectFill" 
        :action="VITE_UPLOAD_BASEURL" 
        :limit="1"
        @change="handleUploadChange"
        @fail="handleUploadFail"
      ></wd-upload>
    </view>
    
    <!-- 是否愿意提供电话号码 -->
    <!-- <view class="!mt-32rpx font-size-24rpx flex-a-center w-center relative">
      <wd-switch v-model="hiddenPhone" :size="20" />
      <wd-text custom-class="ml-12rpx" text="是否愿意提供联系方式" color="#323233"></wd-text>
    </view> -->
    <!-- <view class="position-c-center right-0"
      :class="[hiddenPhone ? 'color-#986DF0' : 'color-#666']"
    >+{{ scoreOption.hiddenPhone }}分</view> -->
    
    <!-- <view class="btn-full w-center pt-40rpx" v-else>
      <wd-button 
        class="btn-w-full btn-h-78"
        @getphonenumber="user.getphonenumber"
        open-type="getPhoneNumber"
      >获取手机号</wd-button>
    </view> -->

    <!-- 实名认证 -->
    <real-name>
      <!-- <template #score>
        <view class="position-c-center right-32rpx font-200 font-size-24rpx"
          :class="[user.userInfo.verificationFlag ? 'color-#986DF0' : 'color-#666']"
        >+{{ scoreOption.verificationFlag }}分</view>
      </template> -->
    </real-name>
    
    <!-- 生成分享图 -->
    <view style="visibility: hidden;position: absolute;left: 0;top: 0;pointer-events: none;">
      <l-painter ref="painter" v-if="imgData.url">
        <l-painter-view css="display: inline-block; width: 750rpx;position: relative;">
          <l-painter-image
            :src="imgData.url"
            css="width: 750rpx; height: 600rpx; object-fit: cover; background: #f5f5f5" 
          />
          <l-painter-view
            css="background: rgba(0,0,0,0.5); width: 750rpx; position: absolute; left: 0; bottom: 0; padding: 12rpx; box-sizing: border-box;"
          >
            <l-painter-text 
              css="color: #fff; font-size: 32rpx;" 
              :text="imgData.text" 
            />
          </l-painter-view>
        </l-painter-view>
      </l-painter>
    </view>

    <!-- 保存征婚资料按钮 -->
    <view class="btn-full w-center pt-40rpx">
      <wd-button 
        class="btn-w-full btn-h-78"
        @click="submit"
        :loading="loading"
      >保存征婚资料</wd-button>
    </view>

    <view class="w-full h-78rpx"></view>
    <wd-popup 
      v-model="showUpload" 
      position="bottom" 
      :safe-area-inset-bottom="true" 
      @close="handleClose"
    >
      <image 
        style="width: 750rpx;height: 608rpx;"
        src="https://api.fytxcq.cn:4000/common-bucket/common/2025-08-10/upload_tip_1754816395818.png" 
      />
      <view class="w-full h-1px bg-#f1f1f1 scale-y-50"></view>
      <view class="w-full h-100rpx bg-#fff flex-center" @click="handleUpload(['camera'])">
        相机
      </view>
      <view class="w-full h-1px bg-#f1f1f1 scale-y-50"></view>
      <view class="w-full h-100rpx bg-#fff flex-center" @click="handleUpload(['album'])">
        从相册中获取
      </view>
      <view class="w-full h-16rpx bg-#FAF7FF"></view>
      <view class="w-full h-100rpx bg-#fff flex-center" @click="handleClose">
        取消
      </view>
    </wd-popup>
  </view>
</template>
  
<script lang="ts" setup>
import RealName from "@/components/real-name.vue";
import LPainter from "@/components/lime-painter/components/l-painter/l-painter.vue";
import LPainterView from "@/components/lime-painter/components/l-painter-view/l-painter-view.vue";
import LPainterImage from "@/components/lime-painter/components/l-painter-image/l-painter-image.vue";
import LPainterText from "@/components/lime-painter/components/l-painter-text/l-painter-text.vue";

import { DeletePersonalImageryInfo, UpdateUserInfo, UpdateUserProfileInfo } from "@/service/db_user";
import { Main } from "@/service/types";
import { User } from "@/service/types/user";
import { useCommonStore, useThemeStore, useUserStore } from "@/store";
import { calculateAge, checkImg, comUploadFile, formatDate } from "@/utils";
import { useMessage, useToast } from "wot-design-uni";

// 主题颜色
const { themeConfig } = useThemeStore();
const useCommon = useCommonStore();
const user = useUserStore();
const toast = useToast();
const message = useMessage();

const preferences = ref('去填写择偶要求'); // 择偶要求
const professionName = ref('');
const schoolName = ref('');

const initFormData = {
  specialNote: '', // 特殊说明
  partnerRequirements: '', // 择偶要求
  loveView: '', // 我的爱情观
  idealPartner: '', // 理想中的Ta
  contactPhone: '', // 联系方式
  userId: user.userInfo.id, // 用户id
  avatarIds: '', // 个人形象照片ID, 多个ID用逗号隔开
  gender: '0', // 性别(0：男，1：女)
  nickname: '', // 昵称
  birthYearMonth: +new Date('1995-01-01'), // 出生年月
  height: 0, // 身高 (单位: cm)
  weight: 0, // 体重 (单位: kg)
  provinceId: '',
  cityId: '',
  districtId: '',

  publishPeopleType: '', // 发布人类型,字典(publish_people_type)
  maritalStatus: '', // 婚姻状况,字典(matrimony)
  educationLevel: '', // 最高学历/文化层次,字典(education)
  profession: '', // 行业/职业,字典(profession)
  incomeStatus: '', // 收入情况,字典(income)
  carHouseStatus	: '', // 车房情况,字典(assets)
  school: '', // 学校,字典(school)
  educationType: '', // 教育类型,字典(educationType)
  phone: undefined, // 手机号

  showPhone: true,
  showWechat: false,
  wechatQrCodeId: '',
}

const formData = reactive({} as typeof initFormData);
const resetFormData = () => {
  for (const key in initFormData) {
    formData[key] = initFormData[key];
  }
}
resetFormData();

// 信息回填
const backfill = () => {
  const { userProfileInfoVo } = user.userInfo || {} as User.UserInfoQueryUserDetail;
  const _userProfileInfoVo = userProfileInfoVo || { nickname: '' } as User.UserProfileInfoVo;
  hiddenPhone.value = !user.userInfo.hiddenPhone;
  
  // if (!_userProfileInfoVo.nickname) return;
  for (const key in formData) {
    if (['userId', 'phone'].includes(key)) continue;
    if (key === 'birthYearMonth') {
      formData[key] = +new Date(_userProfileInfoVo[key]);
      continue;
    }
    const value = _userProfileInfoVo[key];
    formData[key] = value || value === 0 || value === false ? value : initFormData[key];
  }

  const { provinceName, cityName, districtName } = _userProfileInfoVo;
  const labelList = [provinceName, cityName, districtName];
  // 如果地区名称重复, 只留一个
  if (labelList[0] === labelList[1]) {
    labelList.shift();
  }
  city.value = labelList.join('');
  
  user.heightInfo.height = _userProfileInfoVo.height;
  user.heightInfo.weight = _userProfileInfoVo.weight;

  schoolName.value = _userProfileInfoVo.schoolName;
  professionName.value = _userProfileInfoVo.professionName;

  const _wechatQrCodeFile = _userProfileInfoVo.wechatQrCodeFile || {};
  if (_wechatQrCodeFile.preUrl) {
    qrcodeFileList.value = [{ url: _wechatQrCodeFile.preUrl, status: "success", uid: 12346 }];
  }
}

const getImageList = () => {
  const _userProfileInfoVo = user.userInfo.userProfileInfoVo || {} as User.UserProfileInfoVo;
  const list = _userProfileInfoVo.personalImageryInfoVoList || [];
  return list
}

// 联系方式校验
const handleChangeContact = ({ value }, type) => {
  const list = [formData.showPhone, formData.showWechat];
  if (type === 'showPhone' && value && !user.userInfo.phone) {
    formData.showPhone = false;
    return toast.show({ msg: '请先填写手机号！', duration: 3000 });
  }
  if (type === 'showWechat' && value && !formData.wechatQrCodeId) {
    formData.showWechat = false;
    return toast.show({ msg: '请先上传微信二维码！', duration: 3000 });
  }
  if (!value && !list.includes(true)) {
    formData[type] = true;
    toast.show({ msg: '微信二维码和手机号必须二选一!', duration: 3000 });
  }
}

watch(() => formData.wechatQrCodeId, (val) => {
  if (!val) {
    formData.showPhone = true;
    formData.showWechat = false;
  }
})

// 上传文件相关
const qrcodeFileList = ref([]);
const handleUploadChange = ({ fileList: files }) => {
  const file = files[0] || {};
  const resStr = file.response || '';
  const res = resStr ? JSON.parse(resStr) : {};
  const data = res.data || {};
  formData.wechatQrCodeId = data.id || '';
  qrcodeFileList.value = files;
}
const handleUploadFail = ({ error }) => {
  const res = error.data ? JSON.parse(error.data) : {};
  if (res.status == 403) {
    user.clearUserInfo();
    // 403错误  -> 清理用户信息，跳转到登录页
    uni.navigateTo({ url: '/pages/login/index' })
  }
}

// 各分数的配置
// const scoreOption = reactive({
//   personAvatar: 15, // 个人头像
//   personImg: 2, // 个人形象照片5张
//   verificationFlag: 30, // 是否实名
//   hiddenPhone: 30, // 是否愿意提供联系方式
// })
// // 获取置顶分数
// const getScore = computed(() => {
//   let score = 0;
//   // 个人头像
//   if (user.getUseVo.personAvatar.preUrl) {
//     score += scoreOption.personAvatar;
//   }
//   // 是否愿意提供联系方式
//   if (hiddenPhone.value) {
//     score += scoreOption.hiddenPhone;
//   }
//   // 是否实名
//   if (user.userInfo.verificationFlag) {
//     score += scoreOption.verificationFlag;
//   }
//   // 个人形象照片5张
//   for (let i = 1; i <= 5; i++) {
//     if (getFileOptions.value(i).preUrl) {
//       score += scoreOption.personImg;
//     }
//   }
//   return score;
// })

const formRefs = ref();
const errorType = ref<"message" | "toast" | "none">('toast');
const submit = () => {
  const _list = getImageList();
  formData.height = user.heightInfo.height;
  formData.weight = user.heightInfo.weight;

  if (!user.getUseVo.personAvatar.preUrl) return toast.show('请上传个人头像!');
  if (!_list.length) return toast.show('请上传至少一张个人形象照片!');
  if (!user.userInfo.phone) return toast.show('请先获取手机号!');
  if (!formData.height) return toast.show('请选择身高体重！');
  if (!formData.profession) return toast.show('请选择行业/职业！');
  if (!formData.provinceId) return toast.show('请选择居住所在地！');
  if (!user.preferencesDetail.maritalStatus) return toast.show('请先去填写择偶要求');
  if (!user.userInfo.verificationFlag) return toast.show('请实名认证后再保存征婚资料');

  formRefs.value
    .validate()
    .then(({ valid }) => {
      if (!valid) return;

      user.loginSubmit = true;
      const avatarIds = _list.map((item) => {
        return item.id
      }).join(',');
      
      const data = {
        ...formData,
        birthYearMonth: formatDate(new Date(formData.birthYearMonth), 'YYYY-MM-DD'),
        avatarIds,
      }
      
      const list: Main.CheckInfoItem[] = [
        {
          checkType: 'msg',
          content: data.nickname
        },
        {
          checkType: 'msg',
          content: data.specialNote
        },
        {
          checkType: 'msg',
          content: data.partnerRequirements
        },
        {
          checkType: 'msg',
          content: data.loveView
        },
        {
          checkType: 'msg',
          content: data.idealPartner
        },
      ];
      
      _list.forEach(item => {
        const fileInfoVo: any = item.fileInfoVo || {};
        list.push({
          checkType: 'img',
          content: fileInfoVo.preUrl,
          mediaType: 2
        })
      });

      if (user.getUseVo.personAvatar) {
        list.push({
          checkType: 'img',
          content: user.getUseVo.personAvatar.preUrl,
          mediaType: 2
        })
      }

      const _userProfileInfoVo = user.userInfo.userProfileInfoVo || {} as any;
      const _wechatQrCodeFile = _userProfileInfoVo.wechatQrCodeFile || {} as any;
      if (_wechatQrCodeFile.preUrl) {
        list.push({
          checkType: 'img',
          content: _wechatQrCodeFile.preUrl,
          mediaType: 2
        })
      }
      
      useCommon.secCheck({
        userId: user.userInfo.id,
        checkInfoList: list
      }, (resData) => {
        updateUserProfileInfo(data);
      })
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

// base64转换临时路径
function base64ToTempPath(base64Data) {
  const fs = uni.getFileSystemManager()
  const tempFilePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.jpg`
  fs.writeFileSync(tempFilePath, base64Data, 'base64')
  return tempFilePath
}

const imgData = ref<any>({});
const painter = ref();
const getImgData = (data) => {
  const { 
    personalImageryInfoVoList = [],
    provinceName,
    cityName,
    districtName,
    gender,
    birthYearMonth,
    height,
    educationLevelName,
    professionName,
  } = user.userInfo.userProfileInfoVo || {};

  // 第一个位置的图片
  const positionOne = personalImageryInfoVoList.find(item => item.position === 1);
  // 如果没有就用第一张图片
  const firstItem = personalImageryInfoVoList[0];
  const fileItem = positionOne || firstItem || {} as User.PersonalImageryInfoVoItem;
  const _fileInfoVo = fileItem.fileInfoVo || {} as User.FileInfoVo;
  
  // 区域
  const areaName = [provinceName, cityName, districtName].filter((value, index, self) => {
    return self.indexOf(value) === index;
  }).join('');
  // 性别
  const _gender = gender == '0' ? '男' : '女';
  // 年龄
  const age = calculateAge(birthYearMonth);
  // "区域\n性别·年龄·身高\n学历 | 职业" 
  imgData.value = {
    url: _fileInfoVo.preUrl || '',
    text: `${areaName}\n${_gender}·${age}岁·${height}cm\n${educationLevelName} | ${professionName}`,
    res: '',
  }

  setTimeout(() => {
    if (!painter.value) {
      loading.value = false;
      toast.show('保存成功!');
      return;
    }
    painter.value.canvasToTempFilePathSync({
      fileType: 'jpg',
      quality: 0.2,
      success: async (res) => {
        try {
          let tempPath = res.tempFilePath;
          // #ifdef MP-WEIXIN
          const pureBase64 = res.tempFilePath.replace(/^data:image\/\w+;base64,/, '');
          tempPath = base64ToTempPath(pureBase64);
          // #endif

          // 上传图片
          const _res = await comUploadFile({
            url: '/file-info',
            tempFilePath: tempPath,
            formData: {}
          })
          if (_res.code != 200) {
            loading.value = false;
            return toast.show(res.message);
          }
          data.sharePhotoId = _res.data.id;
          // 更新图片到用户信息
          const infoRes = await UpdateUserProfileInfo(data);
          if (infoRes.code != 200) {
            loading.value = false;
            return toast.show(res.message);
          }
          loading.value = false;
          toast.show('保存成功!');
          user.getUserInfo();
        } catch (error) {
          loading.value = false;
          console.log('err => comUploadFile', error);
        }
      },
      fail(e) {
        loading.value = false;
        console.log('err', e);
      }
    })
  }, 500)
}

// 修改用户档案表
const loading = ref(false);
const updateUserProfileInfo = async (data) => {
  try {
    loading.value = true;
    const res = await UpdateUserProfileInfo(data);
    if (res.code != 200) {
      loading.value = false;
      return toast.show(res.message);
    }
    updateUserInfo();
    user.getUserInfo({}, () => {
      getImgData(data);
    });
  } catch (error) {
    loading.value = false;
    console.log(error);
  }
}

const hiddenPhone = ref(false);
// 修改是否隐藏手机号
const updateUserInfo = async() => {
  try {
    const res = await UpdateUserInfo({
      id: user.userInfo.id,
      hiddenPhone: !hiddenPhone.value
    });
    if (res.code != 200) return;
    user.getUserInfo();
  } catch (error) {
    console.log(error);
  }
}

// 获取用户信息的图片
const getFileOptions = computed(() => {
  return (position) => {
    const list = getImageList();
    const data = list.find(item => item.position === position) || {} as any;
    const _fileInfoVo = data.fileInfoVo || { id: '', preUrl: '' };
    return _fileInfoVo;
  }
})

const showUpload = ref(false);
const currentPosition = ref();

const handleClose = () => {
  showUpload.value = false;
  currentPosition.value = null;
}

const handleUpload = (sourceType) => {
  handleUseUpload(currentPosition.value, sourceType);
}

// 上传图片
const uploadImg = async (position = 1) => {
  showUpload.value = true;
  currentPosition.value = position;
}

const handleUseUpload = async (position = 1, sourceType) => {
  const { run } = useUpload({
    userId: user.userInfo.id,
    position,
  }, undefined, { sourceType });

  run(() => {
    user.loginSubmit = true;
    handleClose();
    user.getUserInfo();
  }, checkImg);
}

const uploadAvatar = async () => {
  uni.navigateTo({ url: '/activity/imageCropper' });
  // const { run } = useUpload({
  //   userId: user.userInfo.id
  // }, 'AVATAR')
  // run(() => {
  //   user.loginSubmit = true;
  //   user.getUserInfo();
  // }, checkImg);
}

// 删除弹窗
const deleteConfirm = (position = 1) => {
  message
    .confirm({
      msg: `是否删除该图片？`,
      title: '提示'
    })
    .then(() => {
      deleteImg(position);
    })
    .catch(() => {
      console.log('点击了取消按钮')
    })
}
// 删除图片
const deleteImg = async (position = 1) => {
  try {
    const list = getImageList();
    const data = list.find(item => item.position === position);
    const res = await DeletePersonalImageryInfo({ ids: data.id });
    if (res.code != 200) return toast.show('删除失败！');
    user.getUserInfo();
  } catch (error) {
    console.log(error)
  }
}

// 上传文件相关
// const fileList = ref([]);
// const handleUploadChange = ({ fileList: files }) => {
//   console.log(files)
//   fileList.value = files;
// }
// const handleUploadFail = ({ error }) => {
//   const res = error.data ? JSON.parse(error.data) : {};
//   if (res.status == 403) {
//     // 403错误  -> 清理用户信息，跳转到登录页
//     uni.navigateTo({ url: '/pages/login/index' })
//   }
// }

const toPath = (url) => {
  uni.navigateTo({ url })  
}

const city = ref('');
// 更新城市
function handleUpdateArea(data) {
  if (!data) {
    city.value = '';
    Object.assign(formData, {
      provinceId: undefined, 
      cityId: undefined, 
      districtId: undefined
    })
    return
  }
  
  const [valStr, labelStr] = data.split('/');
  const [provinceVal, cityVal, districtVal] = valStr.split(',');
  const labelList = labelStr.split(',');
  
  // 如果地区名称重复, 只留一个
  if (labelList[0] === labelList[1]) {
    labelList.shift();
  }
  city.value = labelList.join('');
  Object.assign(formData, {
    provinceId: provinceVal, 
    cityId: cityVal, 
    districtId: districtVal
  })
}

// 更新学校/行业
function handleUpdateSchool(_data) {
  if (!_data) return;
  const { type, data } = JSON.parse(_data);
  formData[type] = data.typeCode || '';
  if (type === 'school') {
    schoolName.value = data.typeName || '';
  } else {
    professionName.value = data.typeName || '';
  }
}

onLoad((options) => {
  uni.$on('updateArea', handleUpdateArea);
  uni.$on('updateSchool', handleUpdateSchool);
  
  user.getUserInfo({}, () => {
    backfill();
  });
})

// 页面卸载时移除监听
onUnload(() => {
  uni.$off('updateArea', handleUpdateArea);
  uni.$off('updateSchool', handleUpdateSchool);
})

const setPreferences = () => {
  if (user.preferencesDetail.maritalStatus) {
    preferences.value = '已填写择偶要求';
  } else {
    preferences.value = '去填写择偶要求';
  }
}

onShow(() => {
  setTimeout(() => {
    // 设置页面标题
    themeConfig.title = '完善个人资料';
  }, 0)

  setPreferences();
  user.getPreferencesQueryByUserId(() => {
    setPreferences();
  });
})
</script>

<style lang="scss" scoped>
:root,
page {
  background-color: #fff !important;
}

.textarea-com {
  font-size: 28rpx !important;
  box-sizing: border-box !important;
}

:deep(.uni-textarea-textarea) {
  @extend .textarea-com;
}

:deep(.wot-theme-light) {
  .wd-textarea__inner,
  .uni-textarea-placeholder,
  .uni-textarea-wrapper {
    @extend .textarea-com;
    background-color: #FAF7FF !important;
  }

  .wd-textarea {
    background-color: #FAF7FF !important;
  }
}

:deep(.wot-theme-dark) {
  .wd-textarea,
  .uni-textarea-placeholder,
  .uni-textarea-wrapper {
    background-color: #141414 !important;
  }
}

:deep(.wd-input) {
  padding-right: 44rpx !important;
}

:deep(.wd-cell__right) {
  flex: 2 !important;
}

.percentage-wrap {
  height: 6px;

  :deep(.wd-progress__outer) {
    height: 6px;

    .wd-progress__inner {
      background: #986DF0 !important;
    }
  }
}
</style>
